using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Word;

namespace Kassandra.Core.WordWrapper
{
    public class Word97Wrapper:IWord97Wrapper
    {
        [DllImport("User32.dll")]
        private static extern int ShowWindowAsync(IntPtr hWnd, int swCommand);
        
        private Document _source = null;
        private object missing = Missing.Value;
        private object readOnly = false;
        private object visible = false;
        private ApplicationClass _app;

        public void Load(string fileName)
        {
            if (_app == null)
            {
                _app = new ApplicationClass();
            }

            Documents docs = _app.Documents;

            object sourceFile = fileName;

            _source = docs.Open(ref sourceFile, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref visible, ref missing, ref missing,
                ref missing, ref missing);
        }

        public void SaveAsXmlDocument(string fileName)
        {
            object name = fileName;
            object fileFormat = WdSaveFormat.wdFormatXML;

            _source.SaveAs(ref name, ref fileFormat, ref missing, ref missing,
                                  ref missing, ref missing, ref missing, ref missing,
                                  ref missing, ref missing, ref missing,
                                  ref missing, ref missing, ref missing, ref missing, ref missing);
        }

        public void Dispose()
        {
            const int SW_SHOWMAXIMIZED = 3;
            Process[] wordProcesses = Process.GetProcessesByName("WINWORD");

            if (wordProcesses.Length != 0)
            {
                if (wordProcesses.Length > 1)
                {
//                    DispatchMultipleWordInstanceDelegate();
                }

                if (_app != null)
                {
                    foreach (Process p in wordProcesses)
                    {
                        ShowWindowAsync(p.MainWindowHandle, SW_SHOWMAXIMIZED);
                    }

                    _app.Quit(ref missing, ref missing, ref missing);
                    _app = null;
                    GC.WaitForPendingFinalizers();
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
            }
        }
    }
}